//条件变量的使用
#include<iostream>
#include<cstring>
#include<unistd.h>
#include<vector>
#include<pthread.h>
#include"Mutex.hpp"
#include"Cond.hpp"
using namespace CondModule;
const int NUM = 5;
int cnt = 10;
struct C_M
{
    Mutex mutex;
    Cond cond;
};
struct threaddata
{
    C_M* t;
    std::string name;
};
void* threadrun(void* args)
{
    threaddata* type = static_cast<threaddata*>(args);
    while(true)
    {
    
        LockGuard t = LockGuard(type->t->mutex);//一定不要创建匿名对象
        type->t->cond.Wait(type->t->mutex);
        cnt--;
        std::cout << type->name << ": " << cnt << std::endl;
        //sleep(1);
    }
    return nullptr;
}
int main()
{
    std::vector<pthread_t> tids;
    C_M* type = new C_M();
    Cond c;
    Mutex m;
    type->mutex = m;
    type->cond = c;
    for(int i = 1; i <= NUM; i++)
    {
        threaddata* tmp = new threaddata();
        tmp -> t = type;
        pthread_t tid;
        std::string* name = new std::string(); 
        *name = "pthread - " + std::to_string(i);
        tmp->name = *name;
        pthread_create(&tid,nullptr,threadrun,(void*)tmp);//这里的名字会覆盖小BUG,使用了两个结构体嵌套解决
        std::cout << "创建一个线程成功" << std::endl;
        tids.push_back(tid);
    }
    sleep(3);
    while(true)
    {
        //唤醒线程
        std::cout << "唤醒一个线程..." << std::endl;
        type->cond.Signal();
        sleep(2);
    }
    for(auto x : tids)
    {
        pthread_join(x,nullptr);
        std::cout << "等待一个线程成功" << std::endl;
    }
    return 0;
}